package com.weilan.ark3.tcp;


import com.serotonin.modbus4j.BasicProcessImage;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusSlaveSet;
import com.serotonin.modbus4j.ProcessImage;
import com.serotonin.modbus4j.exception.ModbusInitException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author xmd
 * @Description modbus tcp从站
 * @Date 2024/5/8 17:04
 **/

public class TcpSlave {
    private static final Logger log = LoggerFactory.getLogger(TcpSlave.class);


    public static ModbusSlaveSet slave;

    public static Map<Integer, BasicProcessImage> slaveMap = new HashMap<>();

    public static void createModbusSlave(Set<Integer> slaveIdSet) {
        // 创建一个Modbus TCP从站
        ModbusFactory factory = new ModbusFactory();
        slave = factory.createTcpSlave(false);
        // 在这个从站下创建多个具有不同Slave ID的设备
        slaveIdSet.forEach(e -> slave.addProcessImage(getModbusProcessImage(e)));
        try {
            slave.start();
        } catch (ModbusInitException e) {
            log.error("start tcp slave error,message is:{}", e.getMessage());
        }
    }

    /**
     * 在从站下创建设备
     *
     * @param slaveId 从站id
     * @return 设备镜像
     */
    private static ProcessImage getModbusProcessImage(int slaveId) {
        BasicProcessImage processImage = new BasicProcessImage(slaveId);
        // 允许读取无效地址并设值
        processImage.setAllowInvalidAddress(true);
        processImage.setInvalidAddressValue((short) 0);
        // 初始化保持寄存器的值
//        processImage.setHoldingRegister(1, (short) 2);
        // 添加监听器
//        if (slaveId == 1) {
            processImage.addListener(new SlaveListener());
//        }
        log.info("从站:{} 创建成功", slaveId);
        slaveMap.put(slaveId, processImage);
        return processImage;
    }


}
